/*!
 * BottleCMS-IM v1.2.7 (http://ui.bottlecms.com)
 * Copyright 2014-2018 BottleCMS, Inc.
 * Licensed MIT 
 */

bottlecms.dialogue = {
    elem_target: null,
    server_url: {},
    user_id: null,
    target_id: null,
    me: {},
    he: {},
    lists:[],
    previd: null,
    latestid: null,
    latesttime: null,
    TimeoutDisconnectionText: '抱歉由于您长时间没有发言连接已断开！是否继续?<a href="javascript:;" onClick="_this.keepConnect(this)">继续</a> <a href="javascript:;" onClick="bottlecms.toast(\'结束会话直接关闭窗口即可！\')">结束</a>',
    actiontime: bottlecms.microtime(), //上次动作时间
    connect: true, //连接状态
    actionmaxtime: 5 * 60000, //毫秒没有动作断开连接
    HeartbeatTime: 3000, //心跳间隔时间
    heartogj: null,
    isinit: false,
    loading:false,
    sending:false,
    //窗口拉到底部
    ladong: function() {
        var _this = this;
        setTimeout(function() {
            _this.elem_target.find('.dialogue-main').scrollTop(_this.elem_target.find('.chat_list').height());
        }, 10)
    },
    ftime: function(time) {
        return time.slice(0, 16);
    },
    guid:function () {
        return Number(Math.random().toString().substr(3, 3) + Date.now()).toString(36);
    },

    // 发送栏恢复默认状态
    initelem: function(init_talk) {
        var _this = this;
        _this.elem_target.find('.dialogue-tool').hide();
        _this.elem_target.find('.js_morebtn').show().removeClass("on");
        _this.elem_target.find('.js_sendbtn').hide();
        _this.elem_target.find('.js_emoticonbtn').removeClass("on");
        _this.elem_target.find('.dialogue-emot').hide();
        _this.elem_target.find('.js_voicebtn').show();
        _this.elem_target.find('.js_keyboardbtn').hide();
        _this.elem_target.find('.voicetalkbox').hide();
        _this.elem_target.find('.talkbox').show();
        if(init_talk!==false){
            _this.elem_target.find('.talk_area').val("");
        }

        _this.ladong();
    },
    // 聊天列表html
    showHtml: function(list) {
        var _this = this;
        var newlist = [];
        $.each(list, function(k, v) {
            newlist = [v].concat(newlist);
        });
        var html = ""
        $.each(newlist, function(k, v) {
            html += _this.itemHtml(v);
        });
        return html;
    },


    itemHtml: function(v) {
        var _this = this;

        if (v.word_type == 1) {
            v.words = _this.emoticonreplace(v.words);
        }
        else if (v.word_type == 2) {
            v.words = '<img src="' + v.words + '">';
        }
        else if (v.word_type == 3) {
            v.voice = v.voice || v.words;
            v.words = '<i class="voice"></i><audio class="audio" id="chat_voice_'+v.id+'" preload="" src="' + v.voice + '"></audio>';
        }
        else if (v.word_type == 4) {
            v.video = v.video || v.words;
            v.words = '<video class="video" x5-video-player-type="h5-page" controls="controls" preload="none" src="' + v.video + '"></video>';
        }

        var html = "";
        if(v.created_at){
            v.created_at = _this.ftime(v.created_at);
            html += '<li class="time">' + v.created_at + '</li>';
        }

        var userpic = v.user_id == _this.user_id ? _this.me.pic : _this.he.pic;
        var userclass = v.user_id == _this.user_id ? "me" : "you";
   
        html += '<li class="item '+userclass+' '+(v.temp?'temp':'')+'  word_type' + v.word_type + '" data-type="' + v.word_type + '" data-id="' + v.id + '">';
        html += '   <div class="uinfo"><img src="' + userpic + '" /></div>';
        html += '   <div class="dialogbox"><p class="talk">' + v.words + '</p></div>';
        html += '   <div class="state">'+(v.state||'')+'</div>';
        html += '</li>';
  
        
        return html;
    },



    //发送聊天信息
    sendMessage: function(target_id, word_type, words,temp_id, rfun) {
        var _this = this;
        _this.loading=true;
        
        bottlecms.post(_this.server_url.send_message, {
            word_type: word_type || 1,
            words: words
        }, function(data) {
            if (data.success == true) {
                
            } else if (data.code == 406) {
                // 不是好友
                bottlecms.confirm('<div style="color:#F60;padding:1rem 0;">'+data.msg+'</div>',function(){
                    apply_friend_fun(target_id);
                },function(){
                    bottlecms.back();
                },{
                   confirm_text:'加好友',
                   cancel_text:'返回' 
                });
            } else {
                bottlecms.toast(data.msg);
                _this.elem_target.find(".chat_list .temp[data-id='"+temp_id+"'] .state").html("<font color=red>失败</font>");
            }

        },function(err){
            _this.elem_target.find(".chat_list .temp[data-id='"+temp_id+"'] .state").html("<font color=red>失败</font>");
        },{complete:function(){
            _this.loading=false;
            _this.sending = false;
            _this.getMessage();
        }});
    },
    //获取最近的聊天记录
    getMessage: function() {
        var _this = this;
        if(_this.sending !=false) return false;
        if(_this.loading!=false)return false;
        _this.loading=true;
        bottlecms.get(_this.server_url.get_message, {
            latestid: _this.latestid
        }, function(data) {
            if (data.success == true) {
                if (data.list && data.list.length > 0) {
                    _this.latestid = data.list[0].id;
                    if (!_this.previd) {
                        _this.previd = data.list[data.list.length - 1].id;
                        if (!data.list || data.list.length < 5) _this.elem_target.find('.MessageHistory').remove();
                    }
                    var html = _this.showHtml(data.list);
                    _this.elem_target.find('.chat_list').append(html);
                    _this.elem_target.find(".chat_list .item.temp").remove();
                    _this.ladong();
                }
                
            } else {
                bottlecms.toast(data.msg);
            }
        },null,{complete:function(){
            _this.loading=false;
        }});
    },
    //获取历史消息
    getMessageHistory: function() {
        var _this = this;
        if(_this.loading!=false)return false;
        _this.loading=true;
        bottlecms.get(_this.server_url.get_history_message, {
            previd: _this.previd
        }, function(data) {
            if (data.success == true) {
                if (data.list && data.list.length > 0) {
                    _this.previd = data.list[data.list.length - 1].id;
                    var html = _this.showHtml(data.list);
                    _this.elem_target.find('.chat_list').prepend(html);
                }
                if (!data.list || data.list.length < 5) _this.elem_target.find('.MessageHistory').remove();
            } else {
                bottlecms.toast(data.msg);
            }
        },null,{complete:function(){
            _this.loading=false;
        }});
    },
    //继续会话
    keepConnect: function(thas) {
        var _this = this;
        _this.actiontime = bottlecms.microtime();
        _this.connect = true;
        _this.getMessage();
        $(thas).parent().parent().parent('li').remove();
    },
    //表情包
    emoticon: function(key) {
        var _this = this;
        // var arr = ["鄙视", "闭嘴", "大笑", "发呆", "奋斗", "愤怒", "害羞", "憨笑", "汗", "惊讶", "囧", "骷髅", "困", "脸红", "流泪", "难过", "亲", "耍酷", "睡觉", "挑眉", "吐舌", "微笑", "无辜", "无语", "眩晕", "眼睛发光", "疑问", "猪头", "左顾右盼"];
        var arr = {"鄙视":'despise', "闭嘴":"shutup", "大笑":'laugh', "发呆":"blankly", "奋斗":"struggle", "愤怒":"anger", "害羞":"shy", "憨笑":"sillysmile", "汗":"sweat", "惊讶":"surprised", "囧":"embarrassed", "骷髅":"skeleton", "困":"sleepy", "脸红":"blush", "流泪":"tears", "难过":"sad", "亲":"kiss", "耍酷":"cool", "睡觉":"sleep", "挑眉":"eyebrows", "吐舌":"tongue", "微笑":"smile", "无辜":"innocent", "无语":"speechless", "眩晕":"vertigo", "眼睛发光":"shine", "疑问":"doubt", "猪头":"pighead", "左顾右盼":"lookaround"};
        if (key) {
            if(!arr[key])return false;
            return bc_asset( "bc-application/Home/Assets/Home/img/dialogue/emot/" + arr[key] + ".gif");
        }
        return arr;
    },
    emoticonreplace: function(str) {
        if(!str)return str;
        var _this = this;
        var arr = [];
        var emoticons = _this.emoticon();
        for (var o in emoticons) {
            reg = new RegExp("\\[\/" + o + "\/\\]", "g");
            str = str.replace(reg, '<img src="' + _this.emoticon(o) + '" class="emot" alt="' + o + '" />');
        }
        return str;
    },
    stopget: function() {
        clearTimeout(this.heartogj);
    },
    init: function(paras) {
        var _this = this;
        window.console.log("初始化chat");
        _this.previd = null;
        _this.latestid = null;
        _this.stopget();
        _this.elem_target = paras.elem || $('.bcui-dialogue');
        _this.me = paras.me;
        _this.he = paras.he;
        _this.user_id = _this.me.user_id;
        _this.target_id = _this.he.user_id;
        _this.action = paras.action || "chat";
        _this.server_url = {
            send_message: BOTTLECMS_HOME_PATH + _this.action + '/' + _this.target_id + '/send',
            get_he_message: BOTTLECMS_HOME_PATH + _this.action + '/' + _this.target_id + '/get',
            get_message: BOTTLECMS_HOME_PATH + _this.action + '/' + _this.target_id + '/getall',
            get_history_message: BOTTLECMS_HOME_PATH + _this.action + '/' + _this.target_id + '/getall',
        }
        // 初始化表情
        _this.elem_target.find(".js_emotbox").html("");
        var emoticons = _this.emoticon();
        for (var o in emoticons) {
            _this.elem_target.find(".js_emotbox").append('<li data-val="[/' + o + '/]"><img src="' + _this.emoticon(o) + '"></li>');
        }
        //点击表情按钮
        _this.elem_target.find('.js_emoticonbtn').click(function(e) {
            _this.initelem(false);
            _this.elem_target.find('.js_morebtn').removeClass("on");
            _this.elem_target.find('.dialogue-tool').hide();
            if ($(this).hasClass("on")) {
                $(this).removeClass("on");
                _this.elem_target.find('.dialogue-emot').hide();
            } else {
                $(this).addClass("on");
                _this.elem_target.find('.dialogue-emot').show();
            }
        })
        _this.elem_target.find('.js_emotbox').on("click", "li[data-val]", function(e) {
            var val = $(this).attr("data-val");
            _this.elem_target.find('.talk_area').val(_this.elem_target.find('.talk_area').val() + val);
            if (_this.elem_target.find('.talk_area').val().length > 0) {
                _this.elem_target.find('.js_morebtn').hide();
                _this.elem_target.find('.js_sendbtn').show();
            } else {
                _this.elem_target.find('.js_morebtn').show();
                _this.elem_target.find('.js_sendbtn').hide();
            }
        })
        //更多按钮
        _this.elem_target.find('.js_morebtn').click(function(e) {
            _this.elem_target.find('.js_emoticonbtn').removeClass("on");
            _this.elem_target.find('.dialogue-emot').hide();
            if ($(this).hasClass("on")) {
                $(this).removeClass("on");
                _this.elem_target.find('.dialogue-tool').hide();
            } else {
                $(this).addClass("on");
                _this.elem_target.find('.dialogue-tool').show();
            }
        })
        //获取输出框焦点   
        _this.elem_target.find(".talk_area").focus(function(e) {
            _this.elem_target.find('.js_morebtn').removeClass("on");
            _this.elem_target.find('.dialogue-tool').hide();
            _this.elem_target.find('.js_emoticonbtn').removeClass("on");
            _this.elem_target.find('.dialogue-emot').hide();
        });
        //正在输入
        _this.elem_target.find('.talk_area').bind('input propertychange', function(e) {
            if ($(this).val().length > 0) {
                _this.elem_target.find('.js_morebtn').hide();
                _this.elem_target.find('.js_sendbtn').show();
            } else {
                _this.elem_target.find('.js_morebtn').show();
                _this.elem_target.find('.js_sendbtn').hide();
            }
        });
        //点击发送按钮
        _this.elem_target.find('.js_sendbtn').click(function(e) {
            var words = _this.elem_target.find('.talk_area').val();
            words = bottlecms.trim(words);
            if (!words) return bottlecms.toast("请输入聊天内容！");

            if(_this.sending!=false){
                return bottlecms.toast("请稍后 上一条未发送完成");
            }
            _this.sending=true;
            _this.initelem();
            var temp_id = _this.guid();
            var html = _this.itemHtml({id:temp_id,user_id:_this.user_id,word_type:1,words:words,temp:true,state:'发送中'});
            _this.elem_target.find('.chat_list').append(html);
            _this.ladong();

            _this.sendMessage(_this.target_id,1, words,temp_id);
        })
        _this.elem_target.find('.talk_area').keyup(function(event) {
            event.preventDefault();
            event.stopPropagation();
            if (event.keyCode == 13) {
                _this.elem_target.find('.js_sendbtn').click();
            }
            return false;
        });



        // 点击语音按钮
        _this.elem_target.find('.js_voicebtn').click(function(e) {
            _this.initelem();
            _this.elem_target.find('.js_voicebtn').hide();
            _this.elem_target.find('.js_keyboardbtn').show();
            _this.elem_target.find('.voicetalkbox').show();
            _this.elem_target.find('.talkbox').hide();
        })
        // 点击键盘按钮
        _this.elem_target.find('.js_keyboardbtn').click(function(e) {
            _this.initelem();
        })


        var js_recorder_btn = _this.elem_target.find('.js_holdvoice');
        var recorder_time;

        var startRecord = function() {
            if(!window.wx) {
                return bottlecms.toast("录音不可用")
            }
            if ($(js_recorder_btn).hasClass('on')) {
                return stopRecord();
            }
            $(js_recorder_btn).addClass('on');
            $('.voicetalkpop').show();

            wx.startRecord(); //开始录音
            window.recordObj && clearInterval(window.recordObj);
            recorder_time = 59;
            var timei = 0;
            window.recordObj = setInterval(function() {
                if (recorder_time <= 0) {
                    clearInterval(window.recordObj);
                } else {   
                    timei++;
                    console.log(recorder_time);
                    // $(popup_modal).find('.progressbar div').width((timei/60*100)+"%");
                    // $(popup_modal).find('.titiles').text('剩余' + recorder_time + '秒');
                    recorder_time--;
                }
            }, 1000);

        }
        var stopRecord = function() {
            if(!window.wx) {
                return false;
            }
            clearInterval(window.recordObj);
            if (!$(js_recorder_btn).hasClass('on')) {
                return;
            }
            $(js_recorder_btn).removeClass('on');
            $('.voicetalkpop').hide();
            if (recorder_time < 59) {
                // $(popup_modal).find('.btnbox').hide();
                // $(popup_modal).find('.rebtnbox').show();
            } else {
                bottlecms.toast("时间太短～")
            }

            if(_this.sending!=false){
                return bottlecms.toast("请稍后 上一条未发送完成");
            }
            

            // var loadingobj = bottlecms.loading("发送中～");
            wx.stopRecord({
                success: function(res) {
                    localId = res.localId;


                    _this.sending=true;
                    _this.initelem();
                    var words = "";
                    _this.elem_target.find('.chat_list').append(_this.itemHtml({id:_this.guid(),user_id:_this.user_id,word_type:3,words:words,voice:words,temp:true,state:'发送中'}));

                    // 开始上传
                    console.log('开始上传');
                    wx.uploadVoice({
                        localId: localId, // 需要上传的音频的本地ID，由stopRecord接口获得
                        isShowProgressTips: 1, // 默认为1，显示进度提示
                        success: function(res) {
                            var serverId = res.serverId; // 返回音频的服务器端ID
                            // window.console.log(res)
                            console.log('开始从服务器获取');
                            bottlecms.post(BOTTLECMS_ROOT_PATH + "wechat/loadFile", {
                                serverId: serverId
                            }, function(data) {
                                // loadingobj.close();
                                if (data.success == true) {
                                    // 开始发送
                                    _this.sendMessage(_this.target_id,3, data.obj);
                                    
                                } else {
                                    bottlecms.toast(data.msg);
                                }
                            }, function(err) {
                                // loadingobj.close();
                                bottlecms.toast("转码失败！");
                            })
                        },
                        fail: function(res) {
                            // loadingobj.close(); 
                            bottlecms.toast("转码失败～");
                            // alert("uploadVoice:" + JSON.stringify(res));
                        }
                    });
                },
                fail: function(res) {
                    // loadingobj.close(); 
                    bottlecms.toast("录音失败");
                }
            });
        }

        // 按住说话按钮
        _this.elem_target.find('.js_holdvoice').on('touchstart mousedown', function(e) {
            event.preventDefault();
            event.stopPropagation();
            // window.console.log("touchstart");
            startRecord();
            
        }).on('touchend touchcancel mouseup', function(e) {
            // window.console.log("touchend");
            stopRecord();
            
        });






        //发送图片
       _this.elem_target.find('input[type="file"].js-uppic').change(function(event) {
            if(_this.sending!=false){
                return bottlecms.toast("请稍后 上一条未发送完成");
            }
            bottlecms.log('image')
            _this.sending=true;
            _this.initelem();
            var words = window.URL.createObjectURL(this.files.item(0));
            _this.elem_target.find('.chat_list').append(_this.itemHtml({id:_this.guid(),user_id:_this.user_id,word_type:2,words:words,temp:true,state:'发送中'}));
            _this.ladong(); 

            bottlecms.uploadfile({
                elem:this,
                loading:false,
                success:function(pic){
                    _this.sendMessage(_this.target_id,2,pic);
                }
            })
        });

        //发送视频
        _this.elem_target.find('input[type="file"].js-upvideo').change(function(event) {
            if(_this.sending!=false){
                return bottlecms.toast("请稍后 上一条未发送完成");
            }
            _this.sending=true;
            _this.initelem();

            var words = URL.createObjectURL(this.files.item(0));
            _this.elem_target.find('.chat_list').append(_this.itemHtml({id:_this.guid(),user_id:_this.user_id,word_type:4,words:words,video:words,temp:true,state:'发送中'}));
            _this.ladong();

            
            bottlecms.uploadfile({
                elem:this,
                loading:false,
                maxsize:50,
                success:function(video){
                    _this.sendMessage(_this.target_id,4,video);
                }
            })
        });



        //点击发送礼物
        _this.elem_target.find('.js_giftbtn').click(function(e) {
            _this.initelem();
            gift_fun(_this.target_id, function(data) {
                _this.getMessage();
            })
        })
        //点击查看历史
        _this.elem_target.find('.MessageHistory').click(function() {
            _this.getMessageHistory();
        })
        // 获取最近消息
        _this.elem_target.find('.chat_list').html("");
        _this.getMessage();



        // 播放语音
        _this.elem_target.find('.chat_list').on('click', '.word_type3 .talk', function(event) {
            event.preventDefault();
            var _this= this;
            console.log("播放");
            var _audioDom = $(this).find('.audio')[0];
            
            if(_audioDom.paused){
                _audioDom.play();
            }else{  
                _audioDom.pause();
            }

            _audioDom.addEventListener("pause", function(){ //暂停状态Doing
                console.log("暂停");
                $(_this).find('.voice').removeClass('voice_gif')
                // _playDom.setAttribute('state', 'play');
            }, false);
            _audioDom.addEventListener("play", function(){ //暂停状态Doing
                console.log("播放");
                $(_this).find('.voice').addClass('voice_gif')
                // _playDom.setAttribute('state', 'pause');
            }, false);

            _audioDom.addEventListener('ended', function () {
                console.log("播放完了");
                $(_this).find('.voice').removeClass('voice_gif')
                // change_next(); // 下一曲
            }, false);
        });


        if(window.history.pushState){
            history.pushState(null, null, document.URL);
            var conunt = true;
            window.addEventListener('popstate', function () {
                

                if(conunt==true){
                    history.pushState(null, null, document.URL);
                    if( _this.sending == true){
                        bottlecms.confirm("有消息还没有发送完成，确定要退出吗？",function(){
                            conunt = false;
                            window.history.go(-1);
                            return false;
                        })
                    }else{
                        conunt = false;
                        window.history.go(-1);
                    }

                }else{
                    window.history.go(-1);
                }
                
                
            });
        }
        
        // 开始心跳
        clearInterval(_this.heartogj);
        _this.heartogj = setInterval(function() {
            // 是否还在当前页面
            if ($(document).find(".bcui-dialogue").length < 1) {
                clearInterval(_this.heartogj);
                return;
            }
            if (_this.connect == true) {
                // if ((_this.actiontime + _this.actionmaxtime) < bottlecms.microtime()) { //超时断开连接
                //     _this.connect = false;
                //     _this.elem_target.find('.chat_list').append('<li class="you word_type_0  system"><div class="f_left uinfo"><img src="' + _this.he.pic + '"></div><div class="disbox-flex f_left no_padding  "><p class="talk  ">' + _this.TimeoutDisconnectionText + '</p></div><div class="f_left"></div></li>');
                //     _this.ladong();
                // }
                _this.getMessage();
            }
        }, _this.HeartbeatTime);
        _this.isinit = true;
        return _this;
    }
}